import { AMessage, RedisA, plugin } from '../../api/api'
import {
  _path,
  Write_player,
  existplayer,
  _item,
  _yaml
} from '../../mode/allapi'

export class buing extends plugin {
  constructor() {
    super({
      dsc: '城镇',
      rule: [
        {
          reg: /^(#|\/)?升级.*$/,
          fnc: 'upadd'
        },
        {
          reg: /^(#|\/)?验工*$/,
          fnc: 'seeup'
        }
      ]
    })
  }

  async upadd(e: AMessage) {
    const id = e.user_id
    const thing_user = e.msg 
    const didian = thing_user.replace(/(#|\/)?升级/, '')
    const player = await (await _path(id)).player
    if (player.state == 1) return e.reply('行军中')
    if (!(await existplayer(id))) return false
    const locationMap = {
      草场: player.food_level,
      采石场: player.stone_level,
      伐木场: player.wood_level,
      冶铁台: player.iron_level,
      工坊: player.currency_level,
      仓库: player.warehouse_level,
      城主府: player.ConstructionQuantity
    }
    const level = locationMap[didian]
    const nextlevel = '-' + (level + 1)
    const time1 = (await _yaml()).CD.find(item => item[didian])[didian][
      nextlevel
    ]
    if (!time1) return e.reply(`${didian}已满级`)
    const building = (await _yaml()).upsilver.find(item => item[didian])[
      didian
    ][nextlevel]
    let objArray = []
    let needstone = 0
    let needwood = 0
    let neediron = 0

    if (didian === '城主府') {
      needstone = 3 * building
      needwood = building
      neediron = building
    } else if (didian === '仓库') {
      needstone = (building * 4) / 3
      needwood = building
      neediron = building
    } else if (['工坊', '采石场', '伐木场', '冶铁台'].includes(didian)) {
      needstone = building
      needwood = building
      neediron = building
    } else if (didian === '草场') {
      needstone = building
      needwood = building / 2
      neediron = building / 2
    }

    const json = await RedisA.get('shengji:player:' + id + ':Paction')
    objArray = JSON.parse(json) || [] 
    if (objArray.length >= 5) {
      e.reply('内务府:您已经有五个建筑正在升级中，无法再升级更多的建筑')
      return false
    }
    for (let i = 0; i < objArray.length; i++) {
      if (objArray[i].name == didian) return e.reply(`${didian}在升级中`)
    }
    const now_time = new Date().getTime()
    for (let i = 0; i < objArray.length; i++) {
      const obj = objArray[i]
      const old_time = obj.end_time
      const time = Math.ceil((old_time - now_time) / 1000 / 60)
      if (time <= 0) {
        e.reply('内务府:有建筑已升级完成，还请主公先验工')
        return false
      }
    }
    const requiredLevelMap = {
      仓库: 1,
      草场: 2,
      采石场: 2,
      伐木场: 3,
      冶铁台: 3,
      工坊: 4
    }
    if (
      requiredLevelMap[didian] &&
      player.ConstructionQuantity < requiredLevelMap[didian]
    ) {
      e.reply(
        `内务府：主公，您的城主府等级不足，需要升级到${requiredLevelMap[didian]}级才能升级${didian}`
      )
      return false
    }
    const resourceConditions = [
      {
        didian: '采石场',
        condition: player.wood_num < needwood,
        message: `木材还差${needwood - player.wood_num}`
      },
      {
        didian: '采石场',
        condition: player.iron_num < neediron,
        message: `铁矿还差${neediron - player.iron_num}`
      },
      {
        didian: '伐木场',
        condition: player.stone_num < needstone,
        message: `石头还差${needstone - player.stone_num}`
      },
      {
        didian: '伐木场',
        condition: player.iron_num < neediron,
        message: `铁矿还差${neediron - player.iron_num}`
      },
      {
        didian: '冶铁台',
        condition: player.wood_num < needwood,
        message: `木材还差${needwood - player.wood_num}`
      },
      {
        didian: '冶铁台',
        condition: player.stone_num < needstone,
        message: `石头还差${needstone - player.stone_num}`
      },
      {
        didian: ['仓库', '工坊', '城主府', '草场'],
        condition: player.stone_num < needstone,
        message: `石头还差${needstone - player.stone_num}`
      },
      {
        didian: ['仓库', '工坊', '城主府', '草场'],
        condition: player.wood_num < needwood,
        message: `木材还差${needwood - player.wood_num}`
      },
      {
        didian: ['仓库', '工坊', '城主府', '草场'],
        condition: player.iron_num < neediron,
        message: `铁矿还差${neediron - player.iron_num}`
      }
    ]
    const missingResources = []
    for (const resourceCondition of resourceConditions) {
      if (Array.isArray(resourceCondition.didian)) {
        if (
          resourceCondition.didian.includes(didian) &&
          resourceCondition.condition
        ) {
          missingResources.push(resourceCondition.message)
        }
      } else {
        if (resourceCondition.didian == didian && resourceCondition.condition) {
          missingResources.push(resourceCondition.message)
        }
      }
    }
    if (missingResources.length > 0) {
      e.reply(
        `内务府：主公，您的材料不足，需要补充材料才能升级${didian}。${missingResources.join(
          '，'
        )}`
      )
      return false
    }
    const queue = objArray.length
    const needMoneyMap = {
      2: 1500,
      3: 3000,
      4: 6000
    }
    if (needMoneyMap[queue] && player.currency_num > needMoneyMap[queue]) {
      player.currency_num -= needMoneyMap[queue]
      e.reply(
        `内务府：主公，军中匠户不足，因此花费${needMoneyMap[queue]}五铢钱雇佣匠户`
      )
    } else if (needMoneyMap[queue]) {
      e.reply(
        `内务府：主公，您的五铢钱不足，需要支付${needMoneyMap[queue]}五铢钱才能雇佣额外匠户`
      )
      return false
    }

    if (didian == '采石场') {
      player.wood_num -= needwood
      player.iron_num -= neediron
    } else if (didian == '伐木场') {
      player.stone_num -= needstone
      player.iron_num -= neediron
    } else if (didian == '冶铁台') {
      player.wood_num -= needwood
      player.stone_num -= needstone
    } else {
      player.stone_num -= needstone
      player.wood_num -= needwood
      player.iron_num -= neediron
    }
    Write_player(id, player)
    const brr = {
      Paction: '升级' + didian,
      name: didian, 
      end_time: new Date().getTime() + time1,
      time: time1 
    }
    objArray.push(brr)
    await RedisA.set(
      'shengji:player:' + id + ':Paction',
      JSON.stringify(objArray)
    ) 
    if (didian === '采石场') {
      e.reply(
        '匠户：消耗' +
          needwood +
          '木材，' +
          neediron +
          '铁矿，开始升级预计' +
          time1 / 60 / 1000 +
          '分钟后完成'
      )
    } else if (didian == '伐木场') {
      e.reply(
        '匠户：消耗' +
          needstone +
          '石头，' +
          neediron +
          '铁矿，开始升级预计' +
          time1 / 60 / 1000 +
          '分钟后完成'
      )
    } else if (didian == '冶铁台') {
      e.reply(
        '匠户：消耗' +
          needwood +
          '木材，' +
          needstone +
          '石头，开始升级预计' +
          time1 / 60 / 1000 +
          '分钟后完成'
      )
    } else {
      e.reply(
        '匠户：消耗' +
          needwood +
          '木材，' +
          needstone +
          '石头，' +
          neediron +
          '铁矿，开始升级预计' +
          time1 / 60 / 1000 +
          '分钟后完成'
      )
    }
    return true
  }

  async seeup(e: AMessage) {
    const id = e.user_id
    const img = [] 
    if ((await existplayer(id)) != true) return false
    const player = await (await _path(id)).player
    if (player.state == 1) return e.reply('行军中')
    const json = await RedisA.get('shengji:player:' + id + ':Paction') 
    const objArray = JSON.parse(json) || [] 

    if (objArray.length == 0) {
      img.push('匠户：小人闲暇，还请主公指派')
    }
    const now_time = new Date().getTime()
    for (let i = 0; i < objArray.length; i++) {
      const obj = objArray[i]
      if (obj.name != null && obj.end_time - now_time < 0) {
        const name = obj.name
        const locationMap = {
          草场: player.food_level,
          采石场: player.stone_level,
          伐木场: player.wood_level,
          冶铁台: player.iron_level,
          工坊: player.currency_level,
          仓库: player.warehouse_level,
          城主府: player.ConstructionQuantity
        }
        const nowlevel = locationMap[name]
        const nextlevel = '-' + (nowlevel + 1)
        let income = 0
        if (name == '城主府') {
          player.ConstructionQuantity += 1
        } else {
          income = (await _yaml()).settlement.find(item => item[name])[name][
            nextlevel
          ]
        }
        if (name == '仓库') {
          player.warehouse_level += 1
          player.food_max += income
          player.stone_max += income
          player.wood_max += income
          player.iron_max += income
        } else if (name == '草场') {
          player.food_level += 1
          player.food_production += income
        } else if (name == '采石场') {
          player.stone_level += 1
          player.stone_production += income
        } else if (name == '伐木场') {
          player.wood_level += 1
          player.wood_production += income
        } else if (name == '冶铁台') {
          player.iron_level += 1
          player.iron_production += income
        } else if (name == '工坊') {
          player.currency_level += 1
          player.currency_production += income
        }
        Write_player(id, player)
        objArray.splice(i, 1)
        i--
        img.push(`匠户:${JSON.stringify(obj.name)}竣工,还请主公视察\n`)
      } else {
        const time = Math.ceil((obj.end_time - now_time) / 1000 / 60)
        img.push(
          `匠户:${JSON.stringify(obj.name)}还在修建中剩余时间${time}分钟\n`
        )
      }
    }
    await RedisA.set(
      'shengji:player:' + id + ':Paction',
      JSON.stringify(objArray)
    ) 
    e.reply(img)
    return true
  }
}
